export default{
    namespaced: true,
    state:{
        name:'cart模块',
        carts:[]
    },
    mutations:{
        // 添加到购物车
        SET_CART(state,payload){
            // console.log(payloay) 
            let target = state.carts.find(item => item.id === payload.id)
                if (!target) {
                    //如果没有,创建一条添加进去
                    let obj = {
                        id: payload.id,
                        title: payload.title,
                        price: payload.price,
                        count: 1
                    }
                    state.carts.push(obj)
                }else{
                    // 如果有，数量加1
                    target.count++
                }
        },
        //删除购物车
        DECREASE_CART(state, payload) {
            //找到购物车对应的数据
            let target = state.carts.find(item => item.id === payload.id)
            //让数量减少
            target.count--
            state.carts=state.carts.filter(item=>item.count!==0)
        }
    },
    actions:{
        ADD_TO_CART({commit},payload){
            // 调用自己的mutations
            commit('SET_CART', payload)
            commit('product/DECREASE_INVENTORY',payload,
            { root: true })

        },
        // 移除购物车，从cart组件中获取当前数据
        REMOVE_CART({commit},payload){
            //传给mutations中的DECREASE_CART更改
            commit('DECREASE_CART', payload)
            commit('product/INCREASE_INVENTORY',payload,
            { root: true })

        }
    },
    getters:{
        // 计算总价格
        total(state){
           return (state.carts.reduce((total,item)=>{
            return total+=item.price*item.count
            },0)).toFixed(2)
        }
    },
}